package com.stars.easyms.swagger.plugin;

import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import com.stars.easyms.rest.annotation.EasyMsRestController;
import org.apache.commons.lang3.StringUtils;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.readers.operation.DefaultTagsProvider;

/**
 * <p>className: EasyMsOperationTagsReader</p>
 * <p>description: 设置swagger上显示rest的接口类的名称</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-04 17:36
 */
public final class EasyMsOperationTagsReader implements OperationBuilderPlugin {

    private DefaultTagsProvider tagsProvider;

    public EasyMsOperationTagsReader(DefaultTagsProvider tagsProvider) {
        this.tagsProvider = tagsProvider;
    }

    @Override
    public void apply(OperationContext context) {
        Optional<EasyMsRestController> controllerAnnotation = context.findControllerAnnotation(EasyMsRestController.class);
        if (controllerAnnotation.isPresent() && StringUtils.isNotBlank(controllerAnnotation.get().name())) {
            context.operationBuilder().tags(Sets.newHashSet(controllerAnnotation.get().name()));
        } else {
            context.operationBuilder().tags(getDefaultTagsProvider().tags(context));
        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }

    private DefaultTagsProvider getDefaultTagsProvider() {
        if (tagsProvider == null) {
            tagsProvider = new DefaultTagsProvider();
        }
        return tagsProvider;
    }
}